<script setup lang="ts">
import type { ChangePasswordRequest } from '@/api/endpoints/system/user';
import { changePassword } from '@/api/endpoints/system/user';
import { showSuccess } from '@/lib/toast';
import { DynamicForm } from '@/components/form';
import type { FormSchema } from '@/components/form/types';
import * as z from 'zod';
import { useAuthStore } from '@/stores/auth';

const authStore = useAuthStore();

const loading = ref(false);

// 账号安全表单 Schema
const securityFormSchema: FormSchema = {
  config: {
    fields: [
      {
        name: 'oldPassword',
        type: 'password',
        label: '旧密码',
        placeholder: '请输入旧密码',
        required: true,
        grid: { span: 1 },
      },
      {
        name: 'newPassword',
        type: 'password',
        label: '新密码',
        placeholder: '请输入新密码',
        required: true,
        grid: { span: 1 },
      },
      {
        name: 'confirmPassword',
        type: 'password',
        label: '确认密码',
        placeholder: '请输入确认密码',
        grid: { span: 1 },
      },
    ],
    layout: {
      columns: 1,
      spacing: 'space-y-4',
    },
    submitButton: {
      text: '保存',
    },
    cancelButton: {
      text: '取消',
      show: true,
    },
  },
  validationSchema: z.object({
    id: z.string().optional(),
    oldPassword: z.string().min(6, '密码至少6个字符'),
    newPassword: z.string().min(6, '密码至少6个字符'),
    confirmPassword: z.string().min(6, '密码至少6个字符'),
  }).refine(data => data.newPassword === data.confirmPassword, {
    message: '确认密码与新密码不一致',
    path: ['confirmPassword'],
  }),
  initialValues: {
    id: authStore.user?.id || '',
    oldPassword: '',
    newPassword: '',
    confirmPassword: '',
  },
};

// 处理账号安全表单提交
async function handleSubmitSecurity(values: Record<string, any>) {
  try {
    loading.value = true;
    await changePassword(values as ChangePasswordRequest);
    showSuccess('密码更新成功');
    authStore.logout();
  } finally {
    loading.value = false;
  }
}
</script>

<template>
  <DynamicForm
    class="flex-1 p-12"
    :schema="securityFormSchema"
    :initial-values="securityFormSchema.initialValues"
    :loading="loading"
    :show-cancel-button="false"
    @submit="handleSubmitSecurity"
  />
</template>
